package data;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import fileProcessing.ParsingException;

public class DateEntry extends AbstractDataType<DateEntry>{

	private Date date;
	private String fieldType = "Date";
	
	public DateEntry(){};
	
	public DateEntry(RandomAccessFile raf) throws ParsingException{
		try {
			date = new Date(raf.readLong());
		} catch (IOException e) {
			throw new ParsingException("Error: "+e.getMessage()+" when reading date from table's data file");
		}
	}
	
	public DateEntry(String newDate) throws ParsingException{
		Date temp = parseDate(newDate);
		if(temp != null)
			date = (Date) temp.clone();
	}
	
	public Date parseDate(String d) throws ParsingException{
		SimpleDateFormat dateFormat;
		String [] datePatterns = {"","",""};
		for(String p : datePatterns){
			 dateFormat = new SimpleDateFormat(p);
			 try {
				return dateFormat.parse(d);
			} catch (ParseException e) {
				throw new ParsingException("Invalid date format.");
			}
		}
		return null;
	}

	@Override
	public String toString() {
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
		return sdf.format(date);
	}

	@Override
	public int compareTo(DateEntry o) {
		return date.compareTo(o.date);
	}

	@Override
	public boolean isValid(String s) throws ParsingException {
		if(parseDate(s) != null)
			return true;
		else
			return false;
	}

	@Override
	public String getType() {
		return fieldType;
	}
}
